<template>
  <a-modal
    :visible="visible"
    :title="optionsData.title"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :width="1000"
    @cancel="cancelHandel"
  >
    <div class="cropper-wrapper">
      <vue-cropper
        ref="cropper"
        :img="options.img"
        :info="true"
        :original="true"
        :autoCrop="options.autoCrop"
        :autoCropWidth="options.autoCropWidth"
        :autoCropHeight="options.autoCropHeight"
        :fixedBox="options.fixedBox"
        @realTime="realTime"
      ></vue-cropper>
    </div>
    <div class="result-wrapper">
      <div class="tar-img" :style="previews.div">
        <img :src="previews.url" :style="previews.img" />
      </div>
    </div>
    <template slot="footer">
      <a-button key="back" @click="cancelHandel">取消</a-button>
      <a-button key="downLoad" type="primary" @click="downloadNewImg">下载</a-button>
      <a-button key="submit" type="primary" @click="okHandel">保存</a-button>
    </template>
  </a-modal>
</template>
<script>
import { VueCropper } from 'vue-cropper'
import { imgURLtoFile, fileBase64, DownloadImg } from '@/utils/util'

export default {
  name: 'cropperModal',
  components: {
    VueCropper
  },
  data() {
    return {
      visible: false,
      img: null,
      confirmLoading: false,
      options: this.optionsData,
      previews: {}
    }
  },
  props: {
    optionsData: {
      type: Object,
      default: {}
    }
  },
  methods: {
    edit(record) {
      let { options } = this
      this.visible = true
      this.options = Object.assign({}, options, record)
    },
    cancelHandel() {
      this.options.img = ''
      this.visible = false
    },
    okHandel() {
      const that = this
      that.confirmLoading = true
      // 获取截图的base64 数据
      this.$refs.cropper.getCropData(data => {
        // 转换为File对象
        let file = imgURLtoFile(data, this.options.files.name)
        //将裁剪侯的图片对象返回给父组件
        that.$emit('ok', file)
        that.cancelHandel()
      })
    },
    //下载输入框里的图片
    downloadNewImg() {
      //获取截图的blob数据
      this.$refs.cropper.getCropBlob(data => {
        fileBase64(data).then(res => {
          DownloadImg(res.result, '截图-' + this.options.files.name)
        })
      })
    },
    //移动框的事件
    realTime(data) {
      this.previews = data
    }
  }
}
</script>
 
<style lang="less" scoped>
.cropper-wrapper {
  width: 100%;
  height: 500px;
}
.result-wrapper {
  margin-top: 20px;
  width: 100%;
  display: flex;
  padding: 20px;
  justify-content: center;
  .tar-img {
    overflow: hidden;
  }
}
</style>